package com.bc.bcapi.service;

import com.bc.bccore.redis.RedisService;
import com.bc.bccore.webconfig.WebConfig;
import com.bc.bcmodel.BuyerUserInfo;
import com.bc.bcmodel.consts.GlobalSettings;
import com.bc.bcmodel.consts.RedissCacheKey;
import com.bc.bcmodel.domain.T_ProjectModel;
import com.bc.bcmodel.domain.T_Sendcoin_logModel;
import com.bc.bcmodel.domain.T_User_seller_infoModel;
import com.bc.bcmodel.enums.EmailTemplateEnum;
import com.bc.bcmodel.enums.IntegralRecordEnum;
import com.bc.bcmodel.enums.SendCoinEnum;
import com.bc.bcmodel.req.*;
import com.bc.bcmodel.resp.MngSendEmailResp;
import com.bc.bcmodel.resp.UserCookieResp;
import com.bc.bcmodel.resp.UserInviteResp;
import com.bc.bcmodel.resp.UserinviteListResp;
import com.bc.commoncore.security.AES;
import com.bc.commoncore.security.DES;
import com.bc.commoncore.util.*;
import com.bc.commonentity.common.DBContextDbType;
import com.bc.commonentity.common.DBContextHolder;
import com.bc.commonentity.common.JsonResult;
import com.bc.commonentity.enums.HttpReturnRnums;
import com.bc.commonentity.enums.SeqNameEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mchange.v2.cfg.PropertiesConfigSource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.math.BigInteger;
import java.util.concurrent.TimeUnit;

import com.bc.bcapi.dao.T_User_buyer_infoMapper;
import com.bc.bcmodel.domain.T_User_buyer_infoModel;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Name T_User_buyer_infoService * @Description * @Author generation * @Date 2018/8/12 20:44:11 * @Version 1.0
 **/
@Service
public class T_User_buyer_infoService {
    @Resource
    T_User_buyer_infoMapper t_User_buyer_infoMapper;

    @Resource
    T_SequenceService t_SequenceService;
    @Resource
    CommonImgCodeService commonImgCodeService;
    @Resource
    T_File_upload_logService t_file_upload_logService;
    @Resource
    T_Integral_recordService t_integral_recordService;
    @Resource
    RedisService redisService;
    @Resource
    T_User_walletService t_user_walletService;
    @Resource
    T_Mng_email_sysService t_mng_email_sysService;
    @Resource
    T_Sendcoin_logService t_sendcoin_logService;

    /**
     * 验证邮箱是否使用过(是否已经注册过)
     *
     * @param req
     * @return
     */
    public JsonResult checkEmailUsed(UserEmailCheckReq req) {
        HttpReturnRnums paramsCheckEnum = req.paramsCheck();
        if (paramsCheckEnum != HttpReturnRnums.Success) {
            return new JsonResult(paramsCheckEnum);
        }
        T_User_buyer_infoModel queryModel = new T_User_buyer_infoModel();
        queryModel.setEmail(req.getEmail());
        queryModel.setStatus("1");
        T_User_buyer_infoModel queryResultModel = findByNamedParam(queryModel);
        if (queryResultModel != null) {
//            return new JsonResult(HttpReturnRnums.EMAIL_IS_EXIST);
            return new JsonResult(HttpReturnRnums.Success);
        }
        return new JsonResult(HttpReturnRnums.USER_NOT_EXIST);
    }

    /**
     * 注册
     * status{0:注册未激活;1:注册已激活;}
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = {
            Exception.class}, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public JsonResult signUp(UserBuyerSignUpReq req, HttpServletRequest request) throws Exception {
        HttpReturnRnums paramsCheckEnum = req.paramsCheck();
        if (paramsCheckEnum != HttpReturnRnums.Success) {
            return new JsonResult(paramsCheckEnum);
        }
        String cookie_name = GlobalSettings.BUYERIMGCode_COOKIE_NAME;

        if (!commonImgCodeService.checkCode(request, req.getVcode(), cookie_name)) {
            return new JsonResult(HttpReturnRnums.VCODE_IS_EMPTY);
        }
        T_User_buyer_infoModel queryModel = new T_User_buyer_infoModel();
        queryModel.setEmail(req.getEmail());
        T_User_buyer_infoModel queryResultModel = findByNamedParam(queryModel);
        if (queryResultModel != null) {
            return new JsonResult(HttpReturnRnums.EMAIL_IS_EXIST);
        }
        String userId = t_SequenceService.genSequence(SeqNameEnum.USER_INFO_SEQ);
        T_User_buyer_infoModel insertModel = req.convertorUser(userId);
        int ret = insert(insertModel);
        if (ret <= 0) {
            return new JsonResult(HttpReturnRnums.SystemError);
        }
        //创建用户钱包
        t_user_walletService.createWallet(userId);
        /**
         * 记录邀请
         * */
        setInviteCode(req, userId);
        sendActivateEmail(insertModel, request);
        return new JsonResult(HttpReturnRnums.Success);
    }

    /**
     * 记录邀请
     */
    private void setInviteCode(UserBuyerSignUpReq req, String userId) {

        try {
            if (StringUtils.isEmpty(req.getInviteCode())) {
                return;
            }
            String invite_Userid = DES.decrypt(req.getInviteCode());
            T_User_buyer_infoModel t_user_buyer_infoModel = new T_User_buyer_infoModel();
            t_user_buyer_infoModel.setUser_id(userId);
            t_user_buyer_infoModel.setInvite_code(invite_Userid);
            t_User_buyer_infoMapper.update(t_user_buyer_infoModel);
        } catch (Exception e) {
        }
    }

    /**
     * 登录
     *
     * @param req
     * @param request
     * @param response
     * @return
     */
    public JsonResult logon(UserLogonReq req, HttpServletRequest request,
                            HttpServletResponse response) {
        //base params check
        HttpReturnRnums paramsCheckEnum = req.paramsCheck();
        if (paramsCheckEnum != HttpReturnRnums.Success) {
            return new JsonResult(paramsCheckEnum);
        }
        //暂时不用
//        String cookie_name = GlobalSettings.BUYERIMGCode_COOKIE_NAME;
//        if (!commonImgCodeService.checkCode(request, req.getVcode(), cookie_name)) {
//            return new JsonResult(HttpReturnRnums.VCODE_IS_EMPTY);
//        }
        T_User_buyer_infoModel queryModel = new T_User_buyer_infoModel();
        queryModel.setEmail(req.getEmail());
        queryModel.setPassword(Digest.signMD5(req.getPassWd(), Digest.ENCODE));
        //已激活
        queryModel.setStatus("1");
        T_User_buyer_infoModel queryResultModel = findByNamedParam(queryModel);
        if (queryResultModel == null) {
            return new JsonResult(HttpReturnRnums.LOGON_NAME_PWD_NET_MATCH);
        }
        if (StringUtils.equals("0", queryResultModel.getStatus())) {
            return new JsonResult(HttpReturnRnums.USER_NOT_ACTIVATE);
        }

        //set cooke
        UserCookieResp userCookieResp = new UserCookieResp();
        userCookieResp.setUser_id(queryResultModel.getUser_id());
        userCookieResp.setLogin_time(DateUtil.getToday());
        String userStr = JsonUtil.obj2string(userCookieResp);
        userStr = AES.aesEncrypt(userStr);
        CookieUtils.setCookie(request, response, GlobalSettings.BUYER_COOKIENAME, userStr);
        return new JsonResult(HttpReturnRnums.Success, queryResultModel);
    }

    /**
     * 发送重置密码邮件
     *
     * @param req
     * @return
     */
    public JsonResult sendRestPasswd(UserSendRestPasswdReq req) {
        HttpReturnRnums paramsCheckEnum = req.paramsCheck();
        if (paramsCheckEnum != HttpReturnRnums.Success) {
            return new JsonResult(paramsCheckEnum);
        }
        T_User_buyer_infoModel queryModel = new T_User_buyer_infoModel();
        queryModel.setEmail(req.getEmail());
        T_User_buyer_infoModel queryResultModel = findByNamedParam(queryModel);
        if (queryResultModel == null) {
            return new JsonResult(HttpReturnRnums.USER_NOT_EXIST);
        }
        if (StringUtils.equals("0", queryResultModel.getStatus())) {
            return new JsonResult(HttpReturnRnums.USER_NOT_ACTIVATE);
        }
        sendRestPasswdEmail(queryResultModel);
        return new JsonResult(HttpReturnRnums.Success);
    }

    /**
     * 重置密码
     *
     * @param req
     * @return
     */
    public JsonResult restPasswd(UserRestPasswdReq req) {
        HttpReturnRnums paramsCheckEnum = req.paramsCheck();
        if (paramsCheckEnum != HttpReturnRnums.Success) {
            return new JsonResult(paramsCheckEnum);
        }
        String codeOrg = AES.aesDecrypt(req.getCode());
        if (!StringUtils.contains(codeOrg, "_MARVEL_")) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }
        String[] codeArr = StringUtils.split(codeOrg, "_MARVEL_");
        String userId = codeArr[0];
        String email = codeArr[1];
        T_User_buyer_infoModel queryModel = new T_User_buyer_infoModel();
        queryModel.setEmail(email);
        queryModel.setUser_id(userId);
        T_User_buyer_infoModel queryResultModel = findByNamedParam(queryModel);
        if (queryResultModel == null) {
            return new JsonResult(HttpReturnRnums.USER_NOT_EXIST);
        }
        if (StringUtils.equals("0", queryResultModel.getStatus())) {
            return new JsonResult(HttpReturnRnums.USER_NOT_ACTIVATE);
        }
        T_User_buyer_infoModel updateModel = new T_User_buyer_infoModel();
        updateModel.setId(queryResultModel.getId());
        updateModel.setPassword(Digest.signMD5(req.getPassWd(), Digest.ENCODE));
        update(updateModel);
        return new JsonResult(HttpReturnRnums.Success);
    }

    /**
     * TODO send activate email
     *
     * @param userInfo
     */
    private void sendActivateEmail(T_User_buyer_infoModel userInfo,
                                   HttpServletRequest request) {
        UserPasswordRegisterReq userPasswordRegisterReq = new UserPasswordRegisterReq();
        userPasswordRegisterReq.setUser_id(userInfo.getUser_id());
        userPasswordRegisterReq.setEmail(userInfo.getEmail());
        userPasswordRegisterReq.setCreate_time(DateUtil.getToday());
        String code = JsonUtil.obj2string(userPasswordRegisterReq);
        code = AES.aesEncrypt(code);
        try {
            code = URLEncoder.encode(code, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String email = userInfo.getEmail();
        /**设置激活地址开始*/
        String url = WebConfig.getSitePath() + "/userpassport/activate?code=" + code;
        /**设置激活地址结束*/
        //发送修改密码邮件
        List<MngSendEmailResp> list = new ArrayList<MngSendEmailResp>();
        MngSendEmailResp zhanghao = new MngSendEmailResp();
        zhanghao.setKey("email");
        zhanghao.setValue(email);
        list.add(zhanghao);
        MngSendEmailResp callbackUrl = new MngSendEmailResp();
        callbackUrl.setKey("callbackurl");
        callbackUrl.setValue(url);
        list.add(callbackUrl);

        t_mng_email_sysService.sendSystemEmailSync(
                EmailTemplateEnum.REGISTER, email, JsonUtil.obj2string(list), request);
    }

    /**
     * TODO send activate email
     *
     * @param userInfo
     */
    private void sendRestPasswdEmail(T_User_buyer_infoModel userInfo) {
        String activateCode = AES.aesEncrypt(userInfo.getUser_id() + "_MARVEL_" + userInfo.getEmail());
    }

    /**
     * 保存单条数据     *      * @return
     */

    public int insert(T_User_buyer_infoModel req) {
        return t_User_buyer_infoMapper.insert(req);
    }

    /**
     * 批量增加数据     *      * @return
     */

    public int insertBatch(List<T_User_buyer_infoModel> req) {
        return t_User_buyer_infoMapper.insertBatch(req);
    }

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */

    public T_User_buyer_infoModel findByNamedParam(T_User_buyer_infoModel req) {
        return t_User_buyer_infoMapper.findByNamedParam(req);
    }

    /**
     * 根据对象查询所有数据     *      * @return
     */

    public List<T_User_buyer_infoModel> getAllList(T_User_buyer_infoModel req) {
        return t_User_buyer_infoMapper.findByNamedParamList(req);
    }

    /**
     * 根据对象查询所有分页数据     *      * @return
     */

    public PageInfo<T_User_buyer_infoModel> getList(MngUserBuyerListReq req) {
        PageHelper.startPage(req.getPage_index(), req.getPage_size());
        List<T_User_buyer_infoModel> list = t_User_buyer_infoMapper.getList(req);
        return new PageInfo<T_User_buyer_infoModel>(list);
    }

    /**
     * 更新指定对象     *      * @return
     */

    public int update(T_User_buyer_infoModel req) {
        if (req.getAuth_status() != null && req.getAuth_status() == 1) {
            t_sendcoin_logService.setSendCoin(SendCoinEnum.REGISTERSUCCESS, req.getUser_id(), req.getUser_id());
        }
        return t_User_buyer_infoMapper.update(req);
    }

    /**
     * 删除指定数据     *      * @return
     */

    public int delete(BigInteger id) {
        return t_User_buyer_infoMapper.delete(id);
    }

    /**
     * 根据条件统计数据量     *      * @return
     */

    public long count(T_User_buyer_infoModel req) {
        return t_User_buyer_infoMapper.count(req);
    }

    /**
     * 设置头象
     */
    public JsonResult setHeadFigure(UserSetHeadFigureReq req) {
        JsonResult js = new JsonResult();
        T_User_buyer_infoModel t_user_buyer_infoModel
                = new T_User_buyer_infoModel();
        t_user_buyer_infoModel.setUser_id(req.getUser_id());
        t_user_buyer_infoModel.setHead_figure(t_file_upload_logService.setFilePath(req.getImg_url()));
        t_User_buyer_infoMapper.update(t_user_buyer_infoModel);
        String key = RedissCacheKey.Buyer_UserInfo_Key + req.getUser_id();
        redisService.remove(key);
        return js;
    }

    /**
     * 获取用户总积分
     */
    private int getUserTotalIntegral(String user_id) {
        int integral = 0;
        String key = "getUserTotalIntegral";
        String val = redisService.get(key);
        if (StringUtils.isEmpty(val)) {
            integral = t_User_buyer_infoMapper.getUserTotalIntegral(user_id);
            redisService.set(key, ParseHelper.ToString(integral, "0"), 5, TimeUnit.MINUTES);
        } else {
            integral = ParseHelper.ToInt(val, 0);
        }
        return integral;
    }

    /**
     * 获取买家信息
     */
    public JsonResult userInfo(BuyerUserInfo req) {
        if (StringUtils.isEmpty(req.getHead_figure()) || req.getHead_figure().equals(WebConfig.getImgUrl())) {
            req.setHead_figure(WebConfig.getImgUrl() + "base/no_icon.jpg");
        }
        req.setIntegral(getUserTotalIntegral(req.getUser_id()));
        return JsonResult.get(req);
    }

    /**
     * 获取用户邀请地址
     */
    public JsonResult getInviteCode(String userid) {
        try {
            UserInviteResp resp = new UserInviteResp();
            resp.setSite_path(WebConfig.getSitePath());
            resp.setCode(DES.encrypt(userid));
            return JsonResult.get(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(HttpReturnRnums.ParaError);
    }

    /**
     * 获取我邀请用户列表
     */
    public JsonResult getInviteList(UserInviteListReq req) {
        PageHelper.startPage(req.getPage_index(), req.getPage_size());
        List<UserinviteListResp> list = t_User_buyer_infoMapper.getInviteList(req);
        PageInfo<UserinviteListResp> pageInfo = new PageInfo<UserinviteListResp>(list);
        return new JsonResult(pageInfo);
    }

    /**
     * 通过用户有ID，获取CEOKYC信息
     */
    public JsonResult getCeoKyc(String user_id) {
        JsonResult js = new JsonResult();
        T_User_buyer_infoModel t_user_buyer_infoModel = new T_User_buyer_infoModel();
        t_user_buyer_infoModel.setUser_id(user_id);
        T_User_buyer_infoModel model = t_User_buyer_infoMapper.findByNamedParam(t_user_buyer_infoModel);
        if (model == null) {
            model = new T_User_buyer_infoModel();
        }
        model.setImg_domain(WebConfig.getImgUrl());
        model.setImg_passport_hold(t_file_upload_logService.getFilePath(model.getImg_passport_hold()));
        model.setImg_passport_front(t_file_upload_logService.getFilePath(model.getImg_passport_front()));
        model.setImg_passport_after(t_file_upload_logService.getFilePath(model.getImg_passport_after()));
        model.setImg_address(t_file_upload_logService.getFilePath(model.getImg_address()));
        js.setData(model);
        return js;
    }

    /**
     * 设置当前用户CEOKYC
     */
    @Transactional(rollbackFor = {
            Exception.class}, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public JsonResult setCeoKyc(T_User_buyer_infoModel req, String user_id) {
        JsonResult js = new JsonResult();
        DBContextHolder.setDbType(DBContextDbType.Master.name());
        T_User_buyer_infoModel t_user_buyer_infoModel = new T_User_buyer_infoModel();
        t_user_buyer_infoModel.setUser_id(user_id);
        T_User_buyer_infoModel model = t_User_buyer_infoMapper.findByNamedParam(t_user_buyer_infoModel);
        if (model == null) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }
        if (model.getAuth_status() == 1) {
            return new JsonResult(HttpReturnRnums.CEOKYC_AUTHSUCCESS);
        }
        //默认是草稿
        int status = 0;
        if (req.getAuth_status() != 0) {
            //待审核,需要验证
            status = 2;
            if (req.getTrue_name().isEmpty() ||
                    req.getPassport_code().isEmpty() ||
                    req.getCountry().isEmpty() ||
                    req.getImg_passport_front().isEmpty() ||
                    req.getImg_passport_after().isEmpty() ||
                    req.getImg_passport_hold().isEmpty() ||
                    req.getAddress().isEmpty() ||
                    req.getImg_address().isEmpty()
                    ) {
                return new JsonResult(HttpReturnRnums.ParaError);
            }
        }
        req.setAuth_status(status);
        req.setImg_address(t_file_upload_logService.setFilePath(req.getImg_address()));
        req.setImg_passport_after(t_file_upload_logService.setFilePath(req.getImg_passport_after()));
        req.setImg_passport_front(t_file_upload_logService.setFilePath(req.getImg_passport_front()));
        req.setImg_passport_hold(t_file_upload_logService.setFilePath(req.getImg_passport_hold()));
        t_User_buyer_infoMapper.update(req);
//            t_Project_ceokycMapper.update(req);
//        T_User_buyer_infoModel t_user_buyer_infoModel = new T_User_buyer_infoModel();
//        t_user_buyer_infoModel.setUser_id(user_id);
//        t_user_buyer_infoModel.setCountry(req.getCountry());
//        t_user_buyer_infoMapper.update(t_user_buyer_infoModel);
        return js;
    }
}